package com.da.javatest.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.da.javatest.bean.Worker;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * 利用Apache开源组件poi-3.15导出Excel表
 *
 * @param <T> 应用泛型，适合任何一种javaBean
 */
public class ExportExcel<T> {

    public void exportExcel(String[] headers, Collection<T> dataset, OutputStream out) {
        exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
    }

    /**
     * @param title              表格标题名      
     * @param headers            表格属性列名数组      
     * @param dataset            需要导出的数据      
     * @param out                输出流      
     * @param pattern            如果有时间数据，设定输出格式。默认为“yyy-MM-dd”
     */
    @SuppressWarnings("deprecation")
    public void exportExcel(String title, String[] headers,
                            Collection<T> dataset, OutputStream out, String pattern) {

        // 申明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格的默认列宽为15个字节
        sheet.setDefaultColumnWidth(15);
        // 生成一个样式
        HSSFCellStyle textStyle = workbook.createCellStyle();

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(textStyle);
            cell.setCellValue(headers[i]);
            //设置单元格格式为"文本"
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        }

        //row = sheet.createRow(1);
        //for (int i = 0; i < headers.length; i++) {
        //    HSSFCell cell = row.createCell(i);
        //    cell.setCellStyle(style);
        //    cell.setCellValue("__" + headers[i]);
        //}

        // 遍历集合产生标题行
        Iterator<T> it = dataset.iterator();
        //int index = 1;
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用get方法获得属性值
            Field[] fields = t.getClass().getDeclaredFields();
            // for (int i = 0; i < fields.length; i++) {
            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"
                    + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);

                @SuppressWarnings("unchecked")
                Class<T> tCls = (Class<T>)t.getClass();
                try {
                    Method getmethod = tCls.getMethod(getMethodName,
                        new Class[] {});
                    Object value = getmethod.invoke(t, new Object[] {});
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Date) {
                        Date date = (Date)value;
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                    } else {
                        textValue = value.toString();
                    }

                    // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            HSSFRichTextString richString = new HSSFRichTextString(
                                textValue);
                            HSSFFont font3 = workbook.createFont();
                            font3.setColor(HSSFColor.BLUE.index);
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }

                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }

            }
        }

        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ExportExcel<Worker> ex = new ExportExcel();
        String[] headers = {"ID", "姓名", "工号"};
        List<Worker> dataset = new ArrayList<>();
        dataset.add(new Worker(10000001, "张三", 20));
        dataset.add(new Worker(20000002, "李四", 24));
        dataset.add(new Worker(30000003, "王五", 22));
        try {
            OutputStream out = new FileOutputStream("D://a.xls");
            ex.exportExcel(headers, dataset, out);
            //ex.exportExcel(headers, Collections.EMPTY_LIST, out);
            out.close();
            System.out.println("excel导出成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}